package pl.agh.pp.zephyr.algorithms;

import pl.agh.pp.zephyr.logic.Engine;
import pl.agh.pp.zephyr.model.Host;
import pl.agh.pp.zephyr.model.User;

/**
 * Tworzy RouteRequesty
 * */
public class RouteRequestFactory {

	private final Engine engine;

	public RouteRequestFactory(Engine engine) {
		super();
		this.engine = engine;
	}

	/**
	 * @param callerIP
	 * @param callerPort
	 * @param callerEndpointId
	 * @param callRef
	 * @param virtualQueue
	 * @param callerAlias
	 * @param callId
	 * @param calledIP
	 * @param calledPort
	 * @return RouteRequest na podstawie zadanych parametrów
	 * @throws Exception
	 */
	public RouteRequest createRouteRequest(final String callerIP,
			final String callerPort, final String callerEndpointId,
			final String callRef, final String virtualQueue,
			final String callerAlias, final String callId,
			final String calledIP, final String calledPort) throws Exception {

		return new RouteRequest() {

			final User user;
			final Host host = new Host(calledIP, calledPort);
			
			final String _callRef = callRef;
			final String _callerEndpointId = callerEndpointId;
			{
				// szukanie użytkownika w modelu
				user = engine.area.getElement(new Host(callerIP, callerPort).hashCode(),
						User.class);
				if (user == null) {
					throw new Exception("Caller not found in model : datamodel inconsistent");
				}
				host.setAlias(virtualQueue.split(":")[0]); // TODO wyciągnąć alias -- nazwa, do której dzwonimy? czsaem ma adres i port..
			}

			@Override
			public User getCaller() {
				return user;
			}

			@Override
			public Host getCalled() {
				return host;
			}

			@Override
			public String getCallRef() {
				return _callRef;
			}

			@Override
			public String getCallingEndpointId() {
				return _callerEndpointId;
			}
			
			public String toString() {
				return "RouteRequest from: " + user + ", to: " + host;
			}

		};
	}
}

